package com.yimixian.app.address;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.ta.utdid2.android.utils.StringUtils;
import com.umeng.analytics.MobclickAgent;
import com.yimixian.app.EventBusDomain.ShowAdSelectChange;
import com.yimixian.app.R;
import com.yimixian.app.common.CacheKeys;
import com.yimixian.app.common.Constants;
import com.yimixian.app.common.SharePreferenceKeys;
import com.yimixian.app.common.StatConstants;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.location.LocatedListener;
import com.yimixian.app.location.LocatedListener2;
import com.yimixian.app.location.LocationProvider;
import com.yimixian.app.model.Address;
import com.yimixian.app.model.AppConfig;
import com.yimixian.app.model.City;
import com.yimixian.app.model.Region;
import com.yimixian.app.model.Store;
import com.yimixian.app.rest.YmxDataService;
import com.yimixian.app.rest.api.AddressAPI;
import com.yimixian.app.store.StoreDetailActivity;
import com.yimixian.app.store.StoresView;
import com.yimixian.app.util.ObservableUtils;
import com.yimixian.app.util.SharedPreferencesHelper;
import com.yimixian.app.util.UiUtils;

import de.greenrobot.event.EventBus;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import org.json.JSONObject;

import butterknife.ButterKnife;
import butterknife.InjectView;

import java.util.ArrayList;
import java.util.List;

public class ChooseAddressOrStoreActivity extends ChooseAdOrStHttpActivity implements
        StoresView.Listener {

    public static final String EXTRA_SELECTED_TAB_INDEX = "extra_index";
    public static final String EXTRA_SELECTED_REGION_ID = "extra_region_id";
    public static final String DEFAULT_CITY_NAME = "请选择城市";
    public static final String EXTRA_APPCONFIG_SAVE = "extra_appconfig_save";
    public static final String EXTRA_TOKEN_SAVE = "extra_token_save";

    public static final int ADDRESS_TAB = 0;
    public static final int PICK_UP_TAB = 1;

    @InjectView(R.id.pick_up_tab)
    TextView mPickUpTab;
    @InjectView(R.id.address_tab)
    TextView mAddressTab;
    @InjectView(R.id.view_pager)
    ViewPager mViewPager;

    private FrameLayout mLocatingButton;
    private AddressesView mAddressesView;
    private ProgressBar mProgressBar;
    private ImageView mLocatingIcon;
    private TextView mLocatingText;
    private View mAddAddressButton;

    private View mShowAddressesPage;
    private View mShowPickUpStoresPage;

    private YmxDataService mYmxDataService;
    private DataManager mDataManager;
//    private LocationProvider mLocationProvider;
//    private GeoCoder mBaiduGeoCoder;
//    private Subscription mLocatingSubscription;
    private List<Address> mAddresses;
    private int mSelectedTabIndex;
    private boolean mIsNeedGetPickUpStoresInfo;
    private TextView mPickUpCityText;
    private View mChooseCityView;
    private View mPickUpStoresPageLoadingView;
    private View mAddressesPageLadingView;
    private View mNoStoreView;
    private View mNoStoreTipView;
    private String mCityName;
    private String mCityId;
    private Address mCurrentPosition;
    private Address mAddress;
    private List<Store> mStores;
    private StoresView mStoresView;
    private List<City> mCities = new ArrayList<>();
    private Integer mStoreId;
    private int upLoadStoreId;
    private AddressAPI mAddressAPI;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            String token = savedInstanceState.getString(EXTRA_TOKEN_SAVE, "");
            if (!StringUtils.isEmpty(token)){
                DataManager.getInstance().put(CacheKeys.TOKEN, token);
            }
            AppConfig appConfig = (AppConfig) savedInstanceState.getSerializable(EXTRA_APPCONFIG_SAVE);
            if (appConfig != null) {
                DataManager.getInstance().put(CacheKeys.APP_CONFIG, appConfig);
            }
        }
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
        outState.putInt(ShowAddressesActivity.EXTRA_MODE, mMode);
            outState.putInt(EXTRA_SELECTED_TAB_INDEX, mSelectedTabIndex);
        if (!StringUtils.isEmpty((String)DataManager.getInstance().get(CacheKeys.TOKEN)))
            outState.putString(EXTRA_TOKEN_SAVE, (String)DataManager.getInstance().get(CacheKeys.TOKEN));
        AppConfig appConfig = DataManager.getInstance().get(CacheKeys.APP_CONFIG);
        if (appConfig != null) {
            outState.putSerializable(EXTRA_APPCONFIG_SAVE, appConfig);
        }
    }

    @Override
    public void resumeOnCreate() {
        if (mDataManager != null) {
            return;
        }
        mDataManager = DataManager.getInstance();
        mAddress = SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_ADDRESS);
        if (mAddress != null){
            //首次进来切换那个tab
            mSelectedTabIndex = mAddress.isPickup ? PICK_UP_TAB : ADDRESS_TAB;
            //自定位属于配送
            mStoreId = Integer.parseInt(StringUtils.isEmpty(mAddress.storeId) ? "-1" : mAddress.storeId);
        }else{
//            mSelectedTabIndex = PICK_UP_TAB;
            mSelectedTabIndex = ADDRESS_TAB;
            mStoreId = -1;
        }
        mYmxDataService = YmxDataService.getInstance();
        setContentView(R.layout.choose_address_activity);
        ButterKnife.inject(this);
        initViewPager();
        fetchAddressAndPickUpStores(true);
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    private void initViewPager() {
        LayoutInflater layoutInflater = getLayoutInflater().from(this);
        mShowAddressesPage = layoutInflater.inflate(R.layout.show_addresses_view, null);
        mShowPickUpStoresPage = layoutInflater.inflate(R.layout.show_pick_up_stores_view, null);

        PagerAdapter pagerAdapter = new PagerAdapter() {
            @Override
            public boolean isViewFromObject(View arg0, Object arg1) {

                return arg0 == arg1;
            }

            @Override
            public int getCount() {

                return 2;
            }

            @Override
            public void destroyItem(ViewGroup container, int position,
                                    Object object) {
                container.removeView(getPageByPosition(position));

            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                View page = getPageByPosition(position);
                container.addView(page);
                if (position == ADDRESS_TAB) {
                    initShowAddressesPage();
                } else {
                    initShowPickUpStoresPage();
                }
                return page;
            }

            private View getPageByPosition(int position) {
                return position == ADDRESS_TAB ? mShowAddressesPage : mShowPickUpStoresPage;
            }

        };
        mViewPager.setAdapter(pagerAdapter);
        ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                if (position == ADDRESS_TAB) {
                    mSelectedTabIndex = ADDRESS_TAB;
                    mAddressTab
                            .setBackgroundResource(R.drawable.choose_address_left_tab_bg_pressed);
                    mPickUpTab.setBackgroundResource(R.drawable.choose_address_right_tab_bg_normal);
                    mAddressTab.setTextColor(0xffffffff);
                    mPickUpTab.setTextColor(getResources().getColor(R.color.ymx_orange));
                } else {
                    mSelectedTabIndex = PICK_UP_TAB;
                    mAddressTab.setBackgroundResource(R.drawable.choose_address_left_tab_bg_normal);
                    mPickUpTab
                            .setBackgroundResource(R.drawable.choose_address_right_tab_bg_pressed);
                    mPickUpTab.setTextColor(0xffffffff);
                    mAddressTab.setTextColor(getResources().getColor(R.color.ymx_orange));
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        };
        mViewPager.addOnPageChangeListener(onPageChangeListener);
        mViewPager.setCurrentItem(mSelectedTabIndex);
        onPageChangeListener.onPageSelected(mSelectedTabIndex);
        mAddressTab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MobclickAgent.onEvent(ChooseAddressOrStoreActivity.this,
                        StatConstants.CHOOSE_ADDRESS_TAB_ADDRESS_CLICK);
                mViewPager.setCurrentItem(ADDRESS_TAB);
            }
        });
        mPickUpTab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MobclickAgent.onEvent(ChooseAddressOrStoreActivity.this,
                        StatConstants.CHOOSE_ADDRESS_TAB_PICK_UP_CLICK);
                mViewPager.setCurrentItem(PICK_UP_TAB);
            }
        });
    }

    private void fetchAddressAndPickUpStores(final boolean readFromCache) {
        getAddressesData(readFromCache);
        mIsNeedGetPickUpStoresInfo = false;
        AppConfig appConfig = DataManager.getInstance().get(CacheKeys.APP_CONFIG);
        if (appConfig == null) {
            return;
        }
        List<Region> regions = appConfig.regions;
        if (regions != null){
            mCities = new ArrayList<>();
            for (Region mRegion : regions){
                if (mRegion.cities != null) mCities.addAll(mRegion.cities);
            }
        }
//        mCurrentPosition = SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_POSITION);
        if (mCurrentPosition == null) {
            if (mNoStoreView != null) {
                mNoStoreTipView.setVisibility(View.GONE);
                mPickUpStoresPageLoadingView.setVisibility(View.VISIBLE);
            }

            LocationProvider.getInstance().startBaiduLocated2(false, new LocatedListener2() {

                @Override
                public void locatedSuccessListener(BDLocation location) {
                    if (location == null) {
                        onLocatingFailed();
                        return;
                    }
                    mCurrentPosition = new Address();
                    mCurrentPosition.latitude = String.valueOf(location.getLatitude());
                    mCurrentPosition.longitude = String.valueOf(location.getLongitude());
                    mCurrentPosition.city = location.getCity();
                    initWithCurrentPositionInfo();
                }

                @Override
                public void locatedFailedListener() {
                    mIsNeedGetPickUpStoresInfo = false;
                    mCityName = DEFAULT_CITY_NAME;
                    if (mPickUpCityText != null) {
                        mPickUpCityText.setText(mCityName);
                    }
                    if (mPickUpStoresPageLoadingView != null) {
                        mPickUpStoresPageLoadingView.setVisibility(View.VISIBLE);
                    }
                }
            });
        }else {
            initWithCurrentPositionInfo();
        }

    }

    @Override
    public void fetchDataFromNetwork(String key) {
        initRequestAPI();
    }

    @Override
    public void initRequestAPI() {
        mAddressAPI = new AddressAPI(mDataManager
                .<String>get(CacheKeys.TOKEN), upLoadStoreId, this);
        mPickUpStoresPageLoadingView.setVisibility(View.VISIBLE);
        mAddressAPI.getAddress();
    }

    @Override
    public void onHttpSuccess(String url, JSONObject responseJson) {
        mPickUpStoresPageLoadingView.setVisibility(View.GONE);
        Address mAddress = mAddressAPI.parseJson(responseJson);
        if (mAddress == null) return;
//        mCurrentPosition = SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_POSITION);
//        //刷新当前自提点列表 用经纬度为定位地址(注意：为后期显示距离)    不是服务器返回的自提点地址
//        if (mCurrentPosition != null){
//            mCurrentPosition.setLocateAddress(mAddress);
//            SharedPreferencesHelper.saveAddress(mCurrentPosition, SharePreferenceKeys.CURRENT_POSITION);
//        }
        SharedPreferencesHelper.saveAddress(mAddress, SharePreferenceKeys.CURRENT_ADDRESS);
        Address add = new Address();
        add.id = -1;
        SharedPreferencesHelper.saveAddress(add, SharePreferenceKeys.CURRENT_NO_LOGIN_ADDRESS);
        setResult(RESULT_OK);
        EventBus.getDefault().post(new ShowAdSelectChange());
        finish();
    }

    @Override
    public void OnHttpFailure(String url, String errorMessage) {
        mPickUpStoresPageLoadingView.setVisibility(View.GONE);
    }

    private void initShowPickUpStoresPage() {
        mPickUpCityText = (TextView) mShowPickUpStoresPage.findViewById(R.id.pick_up_city_text);
        mChooseCityView = mShowPickUpStoresPage.findViewById(R.id.choose_city_view);
        mNoStoreView = mShowPickUpStoresPage.findViewById(R.id.no_store_view);
        mNoStoreTipView = mShowPickUpStoresPage.findViewById(R.id.no_store_tip);
        mPickUpStoresPageLoadingView = mShowPickUpStoresPage.findViewById(R.id.loading);
        mStoresView = (StoresView) mShowPickUpStoresPage.findViewById(R.id.stores_view);
        if (!TextUtils.isEmpty(mCityName)) {
            mPickUpCityText.setText(mCityName);
        }
        if (!TextUtils.isEmpty(mCityName) && !mCityName.equals(DEFAULT_CITY_NAME)) {
            mNoStoreTipView.setVisibility(View.VISIBLE);
        }

        if (mStores != null) {
            mNoStoreView.setVisibility(View.GONE);
            mPickUpStoresPageLoadingView.setVisibility(View.GONE);
            mStoresView.setVisibility(View.VISIBLE);
            mStoresView.setListener(this);
            mStoresView.bind(mStores, mStoreId == null ? -1 : mStoreId);
        } else if (!mIsNeedGetPickUpStoresInfo) {
            if (mCurrentPosition == null) {
                mNoStoreView.setVisibility(View.GONE);
                mPickUpStoresPageLoadingView.setVisibility(View.VISIBLE);
            } else {
                mNoStoreView.setVisibility(View.VISIBLE);
                mPickUpStoresPageLoadingView.setVisibility(View.GONE);
            }
            mStoresView.setVisibility(View.GONE);
        }

        mChooseCityView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MobclickAgent.onEvent(ChooseAddressOrStoreActivity.this,
                        StatConstants.CHOOSE_ADDRESS_TAB_PICKUP_CHOOSE_CITY_CLICK);
                Intent intent = new Intent(ChooseAddressOrStoreActivity.this,
                        ChooseCityActivity.class);
                intent.putExtra(ChooseCityActivity.EXTRA_CITY_NAME, mCityName);
                startActivityForResult(intent, Constants.CHOOSE_CITY_REQUEST_CODE);
            }
        });
    }

    //选中自提地址地点击事件监听
    @Override
    public void onStoreClicked(int storeId) {
        MobclickAgent.onEvent(this, StatConstants.CHOOSE_ADDRESS_TAB_PICKUP_STORE_CHOOSE_CLICK);
        upLoadStoreId = storeId;
        fetchData(true, null);
    }

    @Override
    public void onStoreInfoIconClicked(Store store) {
        MobclickAgent.onEvent(this, StatConstants.CHOOSE_ADDRESS_TAB_PICKUP_STORE_INFO_CLICK);
        Intent intent = new Intent(ChooseAddressOrStoreActivity.this, StoreDetailActivity.class);
        intent.putExtra(StoreDetailActivity.EXTRA_STORE, store);
        startActivity(intent);
    }

    //初始化自定义地址view数据
    private void initShowAddressesPage() {
        mLocatingButton = (FrameLayout) mShowAddressesPage.findViewById(R.id.locating_button);
        mAddressesView = (AddressesView) mShowAddressesPage.findViewById(R.id.addresses_view);
        mProgressBar = (ProgressBar) mShowAddressesPage.findViewById(R.id.progress_bar);
        mLocatingIcon = (ImageView) mShowAddressesPage.findViewById(R.id.locating_icon);
        mLocatingText = (TextView) mShowAddressesPage.findViewById(R.id.locating_text);
        mAddressesPageLadingView = mShowAddressesPage.findViewById(R.id.loading);
        mAddAddressButton = mShowAddressesPage.findViewById(R.id.add_address_button);

        if (mAddresses != null) {
            // 网络更新时更新界面,界面初次创建时更新界面,双重刷新机制
            mAddressesView.bind(mAddresses, true);
            mAddressesPageLadingView.setVisibility(View.GONE);
        }

        setAddressViewListener(mAddressesView, mDataManager, true);

        if (mAddresses != null) {
            mAddressesView.bind(mAddresses, true);
        }
        mLocatingButton
                .setVisibility(mMode == ShowAddressesActivity.LOCATE_ADDRESS_MODE ? View.VISIBLE
                        : View.GONE);

        mLocatingButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MobclickAgent.onEvent(ChooseAddressOrStoreActivity.this,
                        StatConstants.CHOOSE_ADDRESS_TAB_ADDRESS_LOCATE_CLICK);
                mLocatingButton.setEnabled(false);
                mLocatingText.setText(getString(R.string.locating));
                mLocatingIcon.setVisibility(View.INVISIBLE);
                mProgressBar.setVisibility(View.VISIBLE);
                LocationProvider.getInstance().startBaiduLocated(true, new LocatedListener() {

                    @Override
                    public void locatedSuccessListener(BDLocation location) {
                    }

                    @Override
                    public void locatedSuccessGeoPoiInfoListener(PoiInfo poiInfo) {
                        getAction1(poiInfo.location, poiInfo);
                    }

                    @Override
                    public void locatedFailedListener() {
                        getErrorAction1();
                    }

                    @Override
                    public void locatedFailedGeoPoiInfoListener() {
                        getErrorAction1();
                    }
                });
            }
        });

        mAddAddressButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MobclickAgent.onEvent(ChooseAddressOrStoreActivity.this,
                        StatConstants.CHOOSE_ADDRESS_ADD_NEW_ADDRESS_CLICK);
                stopLocating();
                Intent intent = new Intent(ChooseAddressOrStoreActivity.this,
                        ModifyOrCreateAddressActivity.class);
                startActivityForResult(intent, Constants.MODIFY_ADDRESS_REQUEST_CODE);
            }
        });
    }

    private void initWithCurrentPositionInfo() {
        mCityName = DEFAULT_CITY_NAME;
        // 百度逆编码结果没有城市信息,暂时这么写
        if (!TextUtils.isEmpty(mCurrentPosition.city)) {
            mCityName = mCurrentPosition.city;
        } else {
            mCityName = mDataManager.get(CacheKeys.CURRENT_POSITION_CITY);
        }
        if (mPickUpCityText != null && !TextUtils.isEmpty(mCityName)) {
            mPickUpCityText.setText(mCityName);
        }
        if (!TextUtils.isEmpty(mCityName) ) {
            for (City mCity : mCities) {
                //此处为了匹配服务器返回不带 “市”
                String name = mCity.name;
                if (name == null || name.length() <= 0) return;
                if (!name.contains("市")) name = name + "市";
                if (mCity.name.equals(mCityName) || name.equals(mCityName)) {
                    mIsNeedGetPickUpStoresInfo = true;
                    mCityId = mCity.id;
                    break;
                }
            }
        }
        if (!mIsNeedGetPickUpStoresInfo && mNoStoreView != null) {
            mNoStoreView.setVisibility(View.VISIBLE);
            mPickUpStoresPageLoadingView.setVisibility(View.GONE);
            mStoresView.setVisibility(View.GONE);
            if (!TextUtils.isEmpty(mCityName)) {
                mNoStoreTipView.setVisibility(View.VISIBLE);
            }
        }
        if (mIsNeedGetPickUpStoresInfo) {
            if (mNoStoreView != null) {
                mNoStoreTipView.setVisibility(View.GONE);
            }
            getPickUpStoresDataAndRefresh();
        }
    }

    private void getAddressesData(final boolean readFromCache) {
        if (mAddressesPageLadingView != null) {
            mAddressesPageLadingView.setVisibility(View.VISIBLE);
        }
        mYmxDataService.getAddresses(readFromCache)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        new Action1<List<Address>>() {
                            @Override
                            public void call(List<Address> addresses) {
                                if (mAddressesPageLadingView != null) {
                                    mAddressesPageLadingView.setVisibility(View.GONE);
                                }
                                if (!readFromCache) {
                                    SharedPreferencesHelper.saveAddresses((ArrayList) addresses, SharePreferenceKeys.ADDRESSES);
                                }
                                mAddresses = addresses;
                                if (mAddressesView != null) {
                                    // 网络更新时更新界面,界面初次创建时更新界面,双重刷新机制
                                    mAddressesView.bind(mAddresses, true);
                                }
                            }
                        },
                        new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                if (mAddressesPageLadingView != null) {
                                    mAddressesPageLadingView.setVisibility(View.GONE);
                                }
                            }
                        }
                );
    }

    private void getPickUpStoresDataAndRefresh() {
        if (TextUtils.isEmpty(mCityId)) {
            if (mNoStoreView != null) {
                mNoStoreView.setVisibility(View.VISIBLE);
                mPickUpStoresPageLoadingView.setVisibility(View.GONE);
                mStoresView.setVisibility(View.GONE);
                return;
            }
        }
        mIsNeedGetPickUpStoresInfo = true;
        if (mNoStoreView != null) {
            mNoStoreView.setVisibility(View.GONE);
            mPickUpStoresPageLoadingView.setVisibility(View.VISIBLE);
        }

        mYmxDataService
                .getStores(Constants.DELIVERY_TYPE_PICK_UP, mCityId,
                        mCurrentPosition == null ? null : mCurrentPosition.longitude,
                        mCurrentPosition == null ?
                                null : mCurrentPosition.latitude
                        , mCurrentPosition == null ? null : Constants.BAIDU_COORD_SYSTEM)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        new Action1<List<Store>>() {
                            @Override
                            public void call(List<Store> stores) {
                                mStores = stores;
                                mPickUpStoresPageLoadingView.setVisibility(View.GONE);
                                if (mStoresView != null) {
                                    mStoresView.setListener(ChooseAddressOrStoreActivity.this);
                                    mStoresView.bind(mStores, mStoreId == null ? -1 : mStoreId);
                                    if (mStores != null && mStores.size() != 0) {
                                        mNoStoreView.setVisibility(View.GONE);
                                        mStoresView.setVisibility(View.VISIBLE);
                                    } else {
                                        mNoStoreTipView.setVisibility(View.VISIBLE);
                                        mNoStoreView.setVisibility(View.VISIBLE);
                                        mStoresView.setVisibility(View.GONE);
                                    }
                                }
                            }
                        },
                        new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {

                            }
                        }
                );

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        onREGResult(requestCode, resultCode);
        if (requestCode == Constants.MODIFY_ADDRESS_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                EventBus.getDefault().post(new ShowAdSelectChange());
                setResult(RESULT_OK);
                finish();
            } else {
                // 无论新建或者修改地址 均会重新获取地址列表并更新缓存
                fetchAddressAndPickUpStores(true);
            }
        }
        if (requestCode == Constants.CHOOSE_CITY_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                mCityId = data.getExtras().getString(EXTRA_SELECTED_REGION_ID);
                mCityName = data.getExtras().getString(ChooseCityActivity.EXTRA_CITY_NAME);
                if (mChooseCityView != null) {
                    mPickUpCityText.setText(mCityName);
                }
                getPickUpStoresDataAndRefresh();
            }
        }
    }

    @Override
    public void setTabIndex(Bundle savedInstanceState) {
        mSelectedTabIndex = savedInstanceState.getInt(EXTRA_SELECTED_TAB_INDEX, ADDRESS_TAB);
    }

    @Override
    public void onLocatingFailed() {
        UiUtils.showToast(this, getString(R.string.locate_fail));
        mLocatingButton.setEnabled(true);
        mLocatingText.setText(getString(R.string.locate_current_position));
        mLocatingIcon.setVisibility(View.VISIBLE);
        mProgressBar.setVisibility(View.INVISIBLE);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected String getTitleBarText() {
        return "选择地址";
    }

    public void stopLocating() {
        if (mLocatingButton.isEnabled()) {
            return;
        }
        mLocatingButton.setEnabled(true);
        mLocatingText.setText(getString(R.string.locate_current_position));
        mLocatingIcon.setVisibility(View.VISIBLE);
        mProgressBar.setVisibility(View.INVISIBLE);
    }

    @Override
    public void onBackPressed() {
        setResult(RESULT_OK);
        super.onBackPressed();
    }
}
